import React from 'react';
import { ThemeProvider, useTheme } from '../context/ThemeContext';
import { UserProvider, useUser } from '../context/UserContext';

// 主题切换组件
const ThemeToggle: React.FC = () => {
  const { theme, toggleTheme, isDark } = useTheme();

  return (
    <div className="theme-toggle" style={{ backgroundColor: theme.background, color: theme.color }}>
      <h3>主题切换</h3>
      <p>当前主题: {isDark ? '深色' : '浅色'}</p>
      <button 
        onClick={toggleTheme}
        style={{ 
          backgroundColor: theme.buttonBackground, 
          color: theme.buttonColor,
          border: `1px solid ${theme.border}`
        }}
      >
        切换主题
      </button>
    </div>
  );
};

// 用户信息组件
const UserProfile: React.FC = () => {
  const { user, logout, updateUser } = useUser();

  if (!user) {
    return <p>请先登录</p>;
  }

  return (
    <div className="user-profile">
      <h3>用户信息</h3>
      <div className="user-info">
        <p><strong>ID:</strong> {user.id}</p>
        <p><strong>姓名:</strong> {user.name}</p>
        <p><strong>邮箱:</strong> {user.email}</p>
        <p><strong>角色:</strong> {user.role}</p>
      </div>
      
      <div className="user-actions">
        <button onClick={() => updateUser({ name: '李四' })}>
          改名为李四
        </button>
        <button onClick={() => updateUser({ role: user.role === 'user' ? 'admin' : 'user' })}>
          切换角色
        </button>
        <button onClick={logout}>登出</button>
      </div>
    </div>
  );
};

// 登录组件
const LoginForm: React.FC = () => {
  const { login } = useUser();

  const handleLogin = (role: 'user' | 'admin') => {
    login({
      id: Math.floor(Math.random() * 1000),
      name: role === 'admin' ? '管理员' : '普通用户',
      email: role === 'admin' ? 'admin@example.com' : 'user@example.com',
      role
    });
  };

  return (
    <div className="login-form">
      <h3>登录</h3>
      <div className="login-buttons">
        <button onClick={() => handleLogin('user')}>以用户身份登录</button>
        <button onClick={() => handleLogin('admin')}>以管理员身份登录</button>
      </div>
    </div>
  );
};

// 嵌套组件示例
const NestedComponent: React.FC = () => {
  const { user } = useUser();
  const { theme } = useTheme();

  return (
    <div className="nested-component" style={{ 
      backgroundColor: theme.background, 
      color: theme.color,
      border: `1px solid ${theme.border}`
    }}>
      <h4>嵌套组件</h4>
      <p>这里可以访问多个Context的数据</p>
      {user && <p>欢迎回来, {user.name}!</p>}
    </div>
  );
};

const UseContextDemo: React.FC = () => {
  return (
    <div className="demo-page">
      <h1>useContext Hook 演示</h1>
      <p className="description">
        useContext用于在组件树中共享数据，避免props drilling（层层传递props）。
      </p>

      <ThemeProvider>
        <UserProvider>
          <div className="context-demo">
            {/* 主题切换 */}
            <section className="demo-section">
              <h2>1. 主题Context</h2>
              <ThemeToggle />
            </section>

            {/* 用户认证 */}
            <section className="demo-section">
              <h2>2. 用户Context</h2>
              <div className="user-demo">
                <LoginForm />
                <UserProfile />
              </div>
            </section>

            {/* 嵌套组件 */}
            <section className="demo-section">
              <h2>3. 嵌套组件访问多个Context</h2>
              <NestedComponent />
            </section>

            {/* 使用要点 */}
            <section className="demo-section">
              <h2>4. 使用要点与最佳实践</h2>
              <div className="best-practices">
                <div className="practice-item">
                  <h3>创建Context</h3>
                  <pre>
{`// 创建Context
const MyContext = createContext(defaultValue);

// 创建Provider
const MyProvider = ({ children }) => {
  const [value, setValue] = useState(initialValue);
  return (
    <MyContext.Provider value={{ value, setValue }}>
      {children}
    </MyContext.Provider>
  );
};

// 自定义Hook
const useMyContext = () => {
  const context = useContext(MyContext);
  if (!context) {
    throw new Error('必须在Provider中使用');
  }
  return context;
};`}
                  </pre>
                </div>

                <div className="practice-item">
                  <h3>使用场景</h3>
                  <ul>
                    <li>主题切换（颜色、字体等）</li>
                    <li>用户认证状态</li>
                    <li>应用配置</li>
                    <li>国际化</li>
                    <li>全局状态管理</li>
                  </ul>
                </div>

                <div className="practice-item">
                  <h3>性能优化</h3>
                  <ul>
                    <li>将Context值分割为多个独立的Context</li>
                    <li>使用useMemo优化复杂对象的传递</li>
                    <li>避免在Context中传递频繁变化的状态</li>
                  </ul>
                </div>
              </div>
            </section>
          </div>
        </UserProvider>
      </ThemeProvider>
    </div>
  );
};

export default UseContextDemo;